package org.extremecomponents.util;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.extremecomponents.table.context.Context;
import org.extremecomponents.table.core.Messages;
import org.extremecomponents.table.core.Preferences;
import org.extremecomponents.table.core.PreferencesConstants;
import org.extremecomponents.table.core.TableModel;
import org.extremecomponents.table.core.TableModelUtils;
import org.extremecomponents.table.core.TableProperties;

/**
 * @author charlie
 * @date 2020年8月2日
 */
public class I18nUtils {
	private static Log logger = LogFactory.getLog(I18nUtils.class);

	public static String i18n(TableModel model, String code) {
		if (!StringUtils.isEmpty(code)) {
			String resourceValue = model.getMessages().getMessage(code);
			if (resourceValue != null) {
				return resourceValue;
			}
		}
		return code;
	}

	public static String i18n(Context context, String code) {
		if (!StringUtils.isEmpty(code)) {
			String resourceValue = getMessages(context).getMessage(code);
			if (resourceValue != null) {
				return resourceValue;
			}
		}
		return code;
	}

	public static Messages getMessages(Context context) {
		Preferences preferences = new TableProperties();
		preferences.init(context, TableModelUtils.getPreferencesLocation(context));
		String messages = preferences.getPreference(PreferencesConstants.MESSAGES);
		try {
			Class classDefinition = Class.forName(messages);
			Messages instance = (Messages) classDefinition.newInstance();
			instance.init(context, TableModelUtils.getLocale(context, preferences, null));
			return instance;

		} catch (Exception e) {
			String msg = "Could not create the messages [" + messages + "]. The class was not found or does not exist.";
			logger.error(msg, e);
			throw new IllegalStateException(msg);
		}
	}

}
